#include "database.h"
#include "date_time.h"
#include "converter.h"
#include "logger.h"
#include "useful_functions.h"
#include "str.h"

void database::prot(const string &message, const string &statement /*= global_empty_string*/, unsigned long long duration /*= 0ULL*/, size_t items /*= 0*/) const {
  if (protocol.length() == 0)
    return;

  string str_cnv1;
  string tmp = date_time().to_string(TIME_FORMAT);
  tmp += ' ';
  tmp += message;
  tmp += ' ';

  const unsigned short after_comma = (unsigned short) ((duration % 1000) / 10);
  const unsigned long long before_comma = (duration / 1000);

  converter::to_string(before_comma, str_cnv1);
  str::prepend(str_cnv1, '0', 3);
  tmp += str_cnv1;
  tmp += '.';

  converter::to_string(after_comma, str_cnv1);
  str::prepend(str_cnv1, '0', 2);
  tmp += str_cnv1;

  if (statement.empty() == true)
    logger::log(protocol.c_str(), tmp); // connect, disconnect
  else {
    converter::to_string((unsigned int) items, str_cnv1);
    str::prepend(str_cnv1, '0', 6);
    tmp += ' ';
    tmp += str_cnv1;
    tmp += ' ';
    tmp += converter::replace_all(statement, '\n', ' ', str_cnv1);
    logger::log(protocol.c_str(), tmp);
  } // else
} // database::prot

bool database::is_connected() {
  return connected;
} // database::is_connected

bool database::is_transaction_active() const {
  return is_in_transaction;
} // database::is_transaction_active

database::database() : protocol(global_empty_string), connected(false), is_in_transaction(false) {
  // nothing to do
} // database::database

database::~database() {
  // nothing to do
} // database::~database
